import React, { Component } from 'react'
import { AtForm, AtInput, AtButton, AtList, AtListItem } from 'taro-ui';
import {View, Text, Picker} from '@tarojs/components';
import Input from '../Input';
import Taro from '@tarojs/taro';
import './index.scss';


export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      formData: {},
      error: {}
    }
    // 支持的控件的渲染函数
    this.hash = {
      input: this.renderInput.bind(this),
      address: this.renderAddress.bind(this),
      date: this.renderDate.bind(this)
    }
  }

  componentWillMount () {
    // 将要渲染的时候记录初始值
    const formData = {};
    (this.props.options || []).forEach(item => {
      if (item.key && item.defaultValue) {
        formData[item.key] = item.defaultValue
      }
    });
    this.setState({ formData });
  }
  componentDidMount () { }
  componentWillUnmount () { }
  componentDidShow () { }
  componentDidHide () { }
  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.value !== this.state.value) {
      // this.setState({ value: nextProps.value })
    }
  }
  // 渲染输入框
  renderInput(item) {
    return <AtInput
      name={item.key}
      title={item.label}
      error={this.state.error[item.key]}
      type={item.inputType || 'text'}
      placeholder={item.placeholder || `请输入${item.label}`}
      value={this.state.formData[item.key]}
      required={item.required}
      onChange={this.handleChange.bind(this, item.key)}
    />
  }
  // 渲染地址输入
  renderAddress(item) {
    const { error } = this.state;
    return <View className="form-list">
      <View className={`label ${item.required ? 'required' : ''} ${error[item.key] ? 'error' : ''}`}>{item.label}</View>
      <Input type="text"
             className="address"
             name={item.key}
             value={this.state.formData[item.key]}
             onInput={this.handleChange.bind(this, item.key)}
             placeholder={item.placeholder || `请输入${item.label}`}/>
    </View>
  }
  // 渲染时间选择器
  renderDate(item) {
    const { error } = this.state;
    return <Picker mode='date'
                   value={this.state.formData[item.key]}
                   onChange={this.handleChange.bind(this, item.key)}>
      <AtList>
        <AtListItem className={`${item.required ? 'required' : ''} ${error[item.key] ? 'error' : ''}`}
                    title={item.label}
                    extraText={this.state.formData[item.key] || item.placeholder || `请选择${item.label}`} />
      </AtList>
    </Picker>
  }

  handleChange(key, value) {
    clearTimeout(this.timer);
    const realValue = value.detail ? value.detail.value : value; // 兼容直接传值与控件中的值
    this.timer = setTimeout(() => {
      this.setState({
        formData: {
          ...this.state.formData,
          [key]: realValue
        },
        error: {
          ...this.state.error,
          [key]: undefined
        }
      })
    }, 320);
  }
  onSubmit() {
    // 必填校验
    const { options } = this.props;
    const { formData } = this.state;
    const error = {};
    options.forEach(item => {
      if (item.required && item.key && !formData[item.key]) {
        error[item.key] = item.label + '是必填项';
      }
    });
    if (JSON.stringify(error) !== '{}') {
      this.setState({ error });
      Taro.showToast({ title: '请填写完整' });
      return;
    }
    this.props.onSubmit && this.props.onSubmit.call(null, JSON.parse(JSON.stringify(formData)))
  }
  onReset() {

  }

  render () {
    const { value, tempValue, showInput, hintList } = this.state;
    const { options = [] } = this.props;
    return (
      <AtForm
        className="self-form"
        onSubmit={this.onSubmit.bind(this)}
        onReset={this.onReset.bind(this)}
      >
        {
          options.map(item => <View>
            {
              this.hash[item.type] && this.hash[item.type].call(this, item)
            }
          </View>)
        }
        <AtButton formType="submit">提交</AtButton>
      </AtForm>
    )
  }
}
